Vue.component('vue-table', {
  template: `
      <div :class="shadowClass" v-if="refresh" class="positionR">
        <div v-if="loading" class="loadBox">
          <div class="loadCon">
            <svg viewBox="25 25 50 50" class="circular">
              <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
            </svg>
          </div>
        </div>
        <div class="tabBigBox" ref="tabBigBox">
          <span ref="lineSpan" class="lineSpan"></span>
          <div class="checkBox" v-show="selectRows.length">
            <div>
              <span style="cursor: pointer" @click="selectAll = false;" class="icon-guanbi iconfont"></span>
              已选择<span class="color0B"> {{selectRows.length}} </span>项
            </div>
            <div style="padding-left: 15px" v-html="checkBtnHtml"></div>
          </div>
          <div class="tabHeadBox" ref="tabHeadBox">
            <table :width="tabAllWidth+'px'" vue>
              <colgroup>
                <col v-for="(item,index) of datalist" :key="item.$index" :width="item.width">
              </colgroup>
              <thead>
                <tr>
                  <th v-for="(item,index) of datalist" :key="item.$index" :class="className(item)" :style="styleCss(item, index)">
                      <div :style="{'width': item.width-(index?25:26) + 'px'}">
                        <span v-if="item.type == 'selection' && item.selectionType == 'multi'">
                          <input type="checkbox" class="yb-checkbox" v-model="selectAll"/>
                        </span>
                        <span v-if="item.type != 'selection'" v-html="getHeaderHtml(item.name, item)"></span>
                        <span :class="{'just':item.sortWay == 'asc','contrary':item.sortWay == 'desc'}"
                              @click="sortFun(item)" class="sortSpan" v-if="item.sortable">
                          <i></i>
                          <b></b>  
                        </span>
                        <span @click="dialog = true" class="setting iconfont icon-shezhi" v-if="item.lastOne"></span>
                      </div>
                      <span class="moveSpan" :ref="'thMoveIndex'+index" @mousedown.stop="widthChangeDown($event, index, item)"></span>
                  </th>
                </tr>
              </thead>
            </table>
          </div>
          <div class="tabBodyBox" ref="tabBodyBox" @scroll="bodyScroll">
            <table :width="tabAllWidth+'px'" vue>
              <colgroup>
                <col v-for="(item,index) of datalist" :key="item.$index" :width="item.width">
              </colgroup>
              <tbody>
                <tr v-for="(item,index) of paramList" :key="item.$index">
                  <td v-for="(itemT,indexT) of datalist" :title="itemT.showOverflowTooltip?getCellHtml(item,itemT,index):''" 
                          :style="styleCss(itemT, indexT)" :class="className(itemT)" :key="itemT.$index" class="tooltipShow">
                      <div :style="{'width': itemT.width-(indexT?25:26) + 'px'}" v-if="itemT.type == 'selection' && itemT.selectionType == 'multi'">
                        <input type="checkbox" v-model="item.$checked" class="yb-checkbox"/>
                      </div>
                      <div v-if="itemT.type != 'selection'" :style="{'width': itemT.width-(indexT?25:26) + 'px'}" v-html="getCellHtml(item,itemT,index)"></div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="pageBox" v-if="paging">
          <span class="totalitySPan">共{{pageData.totality}}条记录</span>
          <div class="sizeSelect">
            <select v-model="pageData.pageSize" @change="pageChange">
              <option value="10">每页10条</option>
              <option value="20">每页20条</option>
              <option value="50">每页50条</option>
            </select>
            <span></span>
          </div>
          <input class="goPageIpt" v-model="pageData.goPageNumber">
          <button class="goPageBtn" @click="goPageBtn">跳转</button>
          <button @click="backPage" class="goOnePageBtn left10"><</button>
          <span>{{pageData.pageNumber}}</span>
          <span>/ {{pageTotalityNumber}}</span>
          <button @click="nextPage" class="goOnePageBtn right10">></button>
        </div>
        <table-drag-modal ref="modal" v-model="dialog" @confirm="updateConfigDatas" />
      </div>
    `,
  data: function () {
    return {
      hasShadowL: false,
      hasShadowR: false,
      clientWidth: 0,
      configDatas: [],
      configDataOrders: [],
      paramList: [],
      dialog: false,
      loading: false,
      // 是否要分页
      paging: false,
      pageData: {
        goPageNumber: 1,
        pageSize: 10,
        pageNumber: 1,
        totality: 0,
        sortField: '',
        sortWay: ''
      },
      refresh: true,
      checkBtnHtml: ''//多选自定义HTML
    }
  },
  computed: {
    tabAllWidth() { //表格应占总宽度
      let divWidth = this.clientWidth; //表格父元素宽度
      let allTdWidth = 0; //现有表格列总宽度
      for (let i = 0; i < this.datalist.length; i++) {
        allTdWidth += this.datalist[i].width * 1;
      }
      // allTdWidth += this.datalist.length; //每列有1px边框
      this.hasShadowL = allTdWidth > divWidth;
      return allTdWidth
    },
    shadowClass() {
      return {
        boxShadowL: this.hasShadowL,
        boxShadowR: this.hasShadowR
      }
    },
    datalist() { //去掉不显示的列
      let arr = [];
      this.configDataOrders.forEach(prop => {
        let item = this.configDatas[prop];
        if (item.show) {
          arr.push(item);
        }
      })
      return arr;
    },
    pageTotalityNumber() {
      return Math.ceil(this.pageData.totality / this.pageData.pageSize)
    },
    // 选择全部
    selectAll: {
      get: function () {
        if (!this.paramList.length) return false;
        return this.paramList.findIndex(item => !item.$checked) == -1;
      },
      set: function (val) {
        this.paramList.forEach(item => {
          this.$set(item, '$checked', val);
        })
      }
    },
    // 选择的行
    selectRows: function () {
      return this.paramList.filter(item => item.$checked);
    }
  },
  methods: {
    setModalData() {
      this.$refs.modal.setColumns(this.modalData.cusColumns, this.modalData.columns);
    },
    update() {
      this.refresh = false;
      this.$nextTick(() => this.refresh = true);
    },
    getHeaderHtml(value, configData) {
      if (value instanceof Function) {
        return value(configData);
      }
      return value
    },
    getCellHtml(rowData, configData, index) { //处理显示信息
      if (configData.type == 'index') { //序号
        if (configData.index instanceof Function) {
          return configData.index(rowData, index);
        } else { //拼页码
          return (this.pageData.pageNumber - 1) * this.pageData.pageSize + index + 1
        }
      } else if (configData.type == 'method') { //自定义内容
        if (configData.cell instanceof Function) {
          return configData.cell(rowData, index);
        }
      }
      return rowData[configData.prop] //其他列
    },
    bodyScroll() { //表格滚动事件
      this.$refs.tabHeadBox.scrollLeft = this.$refs.tabBodyBox.scrollLeft;
      this.hasShadowR = this.$refs.tabBodyBox.scrollLeft > 0;
      if (this.$refs.tabBodyBox.scrollLeft < this.tabAllWidth - document.getElementsByClassName('tabHeadBox')[0].offsetWidth) {
        $('#tabBigBox').addClass('boxShadowL');
      } else {
        $('#tabBigBox').removeClass('boxShadowL');
      }
    },
    className(configData) { //列class
      let className = '';
      // 对齐方式
      className += configData.align == 'left' ? 'tLeft ' : configData.align == 'right' ? 'tRight ' : configData.align == 'center' ? 'tCenter ' : '';
      // 固定位置
      className += configData.fixed == 'left' ? 'pLeft ' : configData.fixed == 'right' ? 'pRight ' : '';
      // 超出隐藏
      // className += configData.showOverflowTooltip ? 'tooltipShow' : ''
      return className
    },
    styleCss(configData, index) { //列style
      let styleCss = '';
      if (configData.fixed == 'left') { //列左固定
        if (index != 0) { //多列固定
          let _left = 0;
          for (let i = 0; i < index; i++) {
            _left += this.datalist[i].width * 1;
          }
          styleCss += `left: ${_left}px;`;
        }
      }
      return styleCss
    },
    pageChange() { //每页条数更改
      this.pageData.pageNumber = 1;
      this.pageData.goPageNumber = 1;
      this.getTableList();
    },
    goPageBtn() { //跳转页数
      this.pageData.pageNumber = this.pageData.goPageNumber;
      this.getTableList();
    },
    backPage() { //上一页
      if (this.pageData.pageNumber <= 1) {
        return
      }
      this.pageData.pageNumber -= 1;
      this.pageData.goPageNumber = this.pageData.pageNumber;
      this.getTableList();
    },
    nextPage() { //下一页
      if (this.pageData.pageNumber >= this.pageTotalityNumber) {
        return
      }
      this.pageData.pageNumber += 1;
      this.pageData.goPageNumber = this.pageData.pageNumber;
      this.getTableList();
    },
    getTableList() {
      // 获取表格数据
      this.getTableData(this.pageData);
    },
    sortFun(item) { //排序
      Object.getOwnPropertyNames(this.configDatas).forEach(prop => {
        if (item.$index != this.configDatas[prop].$index) {
          this.configDatas[prop].sortWay = '';
        }
      })
      if (item.sortWay == '') {
        item.sortWay = 'asc';
        this.pageData.sortWay = 'asc';
      } else if (item.sortWay == 'asc') {
        item.sortWay = 'desc';
        this.pageData.sortWay = 'desc';
      } else if (item.sortWay == 'desc') {
        item.sortWay = '';
        this.pageData.sortWay = '';
      }
      this.pageData.sortField = item.sortField;
      this.pageData.pageNumber = 1;
      this.pageData.goPageNumber = 1;
      this.getTableList();
    },
    widthChangeDown(e, index, item) { //改变列宽度
      let _this = this;
      let _span = this.$refs['thMoveIndex' + index][0];
      let moveX = 0; //移动宽度
      let boxClientX = this.$refs.tabBigBox.getBoundingClientRect().left; //表格距离浏览器左边距离
      $(this.$refs.tabHeadBox).on('mousemove', function (event) {
        moveX = event.clientX - e.clientX; //鼠标移动位置
        if (moveX > 0) { //放大
          $(_this.$refs.lineSpan).css('left', event.clientX - boxClientX);
        } else if (moveX < 0) { //缩小
          if (item.width * 1 + moveX < 50) {
            $(_this.$refs.lineSpan).css('left', $(_span).parent().offset().left + 50);
          } else {
            $(_this.$refs.lineSpan).css('left', event.clientX - boxClientX);
          }
        }
      })
      $(this.$refs.tabHeadBox).on('selectstart', function (e) {
        return false
      })
      $('body').on('mouseup', function (e) {
        $(_this.$refs.tabHeadBox).unbind('mousemove'); //移除事件
        $(_this.$refs.tabHeadBox).unbind('selectstart'); //移除事件
        $('body').unbind('mouseup'); //移除事件
        if (moveX > 0) { //放大
          _this.$set(_this.configDatas[index], 'width', _this.configDatas[index].width * 1 + moveX);
        } else if (moveX < 0) { //缩小
          if (_this.configDatas[index].width * 1 + moveX < 50) {
            _this.$set(_this.configDatas[index], 'width', 50);
          } else {
            _this.$set(_this.configDatas[index], 'width', _this.configDatas[index].width * 1 + moveX);
          }
        }
        $(_this.$refs.lineSpan).css('left', '-2000px');
        // 修改缓存
        _this.setCache(_this.cacheKey, _this.options);
        _this.$refs.modal.setColumns(null, _this.modalData.columns);
      })
    },
    // 获取选择的行

    updateConfigDatas(columns) {
      let orders = [];
      this.options.columns = [];
      if (this.configDatas[0].type == 'selection') {
        this.options.columns.push(this.configDatas[0]);
        orders.push(0);
      }
      columns.forEach(item => {
        let data = this.configDatas[item.$index];
        data.show = item.show;
        data.fixed = item.fixed || '';
        data.width = item.width;
        orders.push(item.$index);
        this.options.columns.push(data);
      })
      this.configDataOrders = orders;
      this.setCache(this.cacheKey, this.options);
    }
  },
})
